package com.example.myapplication.dao;

import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;

import com.example.myapplication.entity.User;

import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;


public class ConfirmDao {
    public Boolean flag = false;
    public Boolean ischannged = false;
    public static boolean islogin = true;
    public static String username = "我是星星";
    HttpURLConnection conn;

    // 第一个参数是account，第二个是passwd

    public void send(String account, String password, Handler handler) {

        new Thread(() -> {
            try {
                //获得Connection
                URL url = new URL(HttpDao.urladd + "Confirm");
                conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("POST");
                //上传参数 实现post
                OutputStreamWriter outputStreamWriter = new OutputStreamWriter(conn.getOutputStream());
                BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
                bufferedWriter.write("account=" + account + "&passwd=" + password);
                bufferedWriter.flush();
                //获得数据传入flag 并改变ischanged
                DataInputStream inputStream = new DataInputStream(conn.getInputStream());
                ObjectInputStream objectInputStream = new ObjectInputStream(conn.getInputStream());
                flag = inputStream.readBoolean();
                User user = (User) objectInputStream.readObject();
                inputStream.close();
                //返回messege，int arg1即认证结果0或1
                Message message = handler.obtainMessage();
                message.what = 1;
                message.arg1 = flag ? 1 : 0;
                message.obj = user;
                handler.sendMessage(message);

            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
            }

        }).start();

    }

}

